﻿using System.Text.Json;
using System.Text.Json.Serialization;

namespace Away.IdentityServer.Core.Utils;

public class ApiResult
{
    public static IResult Data(object value)
    {
        return TypedResults.Json(value);
    }

    public static IResult Page<T>(int total, List<T> items)
    {
        return Ok(new PageResultModel<T>()
        {
            Total = total,
            Items = items
        });
    }

    public static IResult Ok(int code = 0, string message = "")
    {
        var result = new ApiResultModel { Code = code, Message = message };
        return Data(result);
    }

    public static IResult Ok<T>(T data, int code = 0, string message = "")
    {
        var result = new ApiResultModel<T> { Code = code, Message = message, Result = data };
        return Data(result);
    }
}

public class ApiResultModel
{
    private string _msg = string.Empty;

    /// <summary>
    /// 状态码 0成功
    /// </summary>
    public int Code { get; set; }

    /// <summary>
    /// 说明
    /// </summary>
    public string Message
    {
        get => string.IsNullOrWhiteSpace(_msg) ? string.Empty : _msg.Trim();
        set => _msg = value;
    }

    public bool Success => Code == 0;

    public ApiResultModel() { }
}

public class ApiResultModel<T> : ApiResultModel
{
    /// <summary>
    /// 数据
    /// </summary>
    public required T Result { get; set; }

    public ApiResultModel() { }
}

public class PageResultModel<T>
{
    private List<T> _items = new();

    public int Total { get; set; }
    public List<T> Items
    {
        get => _items ?? new List<T>();
        set => _items = value;
    }

    public PageResultModel() { }
}

public sealed class DateTimeConverter : JsonConverter<DateTime>
{
    private readonly string _format = "yyyy-MM-dd HH:mm:ss";

    public DateTimeConverter()
    {

    }
    public DateTimeConverter(string format)
    {
        _format = format;
    }

    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        return DateTime.Parse(reader.GetString() ?? string.Empty);
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString(_format));
    }
}